home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 266 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: news.netzone.com!usenet
  2. From: steveng@netzone.com (Steven Gavette)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Pointers to structures
  5. Date: 3 Jan 1996 20:13:48 GMT
  6. Organization: NetZone, Inc.  (602) 991-4NET
  7. Message-ID: <4ceo1s$fhe@news1.netzone.com>
  8. References: <4cc9r4$m26@armitage.cyberspace.com> <DKLDnH.96B@eskimo.com>
  9. NNTP-Posting-Host: phx-ip-49.netzone.com
  10. X-Newsreader: WinVN 0.99.7
  11.  
  12. In article <DKLDnH.96B@eskimo.com>, mag@eskimo.com says...
  13. >
  14. >In article <4cc9r4$m26@armitage.cyberspace.com> (2 Jan 1996 21:59:00 GMT), 
  15. icaru
  16. >s@loomis 
  17. >says :
  18. >>
  19. >>I'm having trouble using a pointer to a struct.  The idea is to have a 
  20. >>struct get filled by a function, which gets the address and everything 
  21. >>via function(struct type*).  Very straightforward.  However, if I try to 
  22. >>CHANGE anything in the struct, it just goes back when the function is 
  23. >>over.  So, let's pretend this imaginary structure is what I'm using:
  24. >>
  25. >>struct st1 {
  26. >>  char *name;
  27. >>  int yadda;
  28. >>};
  29. >>
  30. >>And the function is:
  31. >>
  32. >>fn1(struct st1 *st)
  33. >>{
  34. >>  st = (struct st1*)malloc(sizeof(struct st1*));
  35. >>  st->name = (char*)malloc(16);
  36. >>  strcpy(st->name,"Test");
  37. >>  st->yadda = 100;
  38. >>}
  39. >>
  40. >>At the last line of code in fn1, all the values are correct;  st->name is 
  41. >>"Test" and st->yadda is 100.  As soon as it exits, however, st->name 
  42. >>points to NULL and st->yadda is zero.  The allocation of the structure in 
  43. >>the first line of fn1 doesn't seem to matter;  both ways, I get NULL 
  44. >>pointers coming out of my ears.
  45. >>
  46.  
  47. I think your problem is that you're not returning the new address to the 
  48. calling function. If you want to create the structure in your "fill" 
  49. function, there's no need to pass it a pointer. But you DO need to return it. 
  50. If you are in fact passing the "fill" function a pointer to an existing 
  51. structure, there's no need to allocate memory for it. You need to choose 
  52. which way you're going to do it.
  53.  
  54. Steve
  55.  
  56.